import { h, createVNode } from 'vue'
import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from 'vue-router'
import { useAccountStore, useRoleStore } from '@/stores/account'
import { storeToRefs } from 'pinia'
import path from 'path-browserify'
import { message as Message, Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import app from '@/main.js'

async function addProgressbar(component) {
  app?.config?.globalProperties?.$progressBar?.start()
  await component
  app?.config?.globalProperties?.$progressBar?.end()
  return component
}

export let routes = [
  {
    path: '/private',
    name: 'private',
    component: () => import('@/layout/private-layout/private-layout.vue'),
    children: [
      {
        path: 'db-management/project',
        name: 'db-management/project',
        meta: {
          title: '项目数据',
          breadcrumb: [{ label: '数据库管理' }, { label: '当前页面' }],
          roles: ['normal'],
          type: 'project',
        },
        component: () =>
          addProgressbar(import('@/views/db-management/db-management.vue')),
      },
      {
        path: 'db-management/library',
        name: 'db-management/library',
        meta: {
          title: '库数据',
          breadcrumb: [{ label: '数据库管理' }, { label: '当前页面' }],
          roles: ['normal'],
          type: 'library',
        },
        component: () =>
          addProgressbar(
            import('@/views/db-management-library/db-management-library.vue'),
          ),
      },
      {
        path: 'db-management/personal',
        name: 'db-management/personal',
        meta: {
          title: '个人数据',
          breadcrumb: [{ label: '数据库管理' }, { label: '当前页面' }],
          roles: ['normal'],
          type: 'personal',
        },
        component: () =>
          addProgressbar(
            import('@/views/db-management-personal/db-management-personal.vue'),
          ),
      },
      {
        path: 'db-management/engineering',
        name: 'db-management/engineering',
        meta: {
          title: '工程数据',
          breadcrumb: [{ label: '数据库管理' }, { label: '当前页面' }],
          roles: ['normal'],
          type: 'engineering',
        },
        component: () =>
          addProgressbar(
            import(
              '@/views/db-management-engineering/db-management-engineering.vue'
            ),
          ),
      },

      {
        path: 'db-management-preview/:categoryId/:id/:fileid',
        name: 'db-management-preview',
        meta: {
          breadcrumb: [
            { label: '数据库管理' },
            { label: '项目数据', path: '/private/db-management/project' },
            { label: '当前页面' },
          ],
          roles: ['normal'],
          hasBack: true,
        },
        component: () =>
          addProgressbar(
            import('@/views/db-management-preview/db-management-preview.vue'),
          ),
      },
      {
        path: 'db-management-preview-personal/:categoryId/:id/:fileid',
        name: 'db-management-preview-personal',
        meta: {
          breadcrumb: [
            { label: '数据库管理' },
            { label: '个人数据', path: '/private/db-management/personal' },
            { label: '当前页面' },
          ],
          roles: ['normal'],
          hasBack: true,
        },
        component: () =>
          addProgressbar(
            import(
              '@/views/db-management-preview-personal/db-management-preview-personal.vue'
            ),
          ),
      },
      {
        path: 'db-management-preview-library/:categoryId/:id/:fileid',
        name: 'db-management-preview-library',
        meta: {
          breadcrumb: [
            { label: '数据库管理' },
            { label: '库数据', path: '/private/db-management/library' },
            { label: '当前页面' },
          ],
          roles: ['normal'],
          hasBack: true,
        },
        component: () =>
          addProgressbar(
            import(
              '@/views/db-management-preview-library/db-management-preview-library.vue'
            ),
          ),
      },
      {
        path: 'user-management',
        name: 'user-management',
        meta: { title: '人员管理', roles: ['system'] },
        component: () =>
          addProgressbar(import('@/views/user-management/user-management.vue')),
      },
      {
        path: 'rights-management',
        name: 'rights-management',
        meta: { title: '权限管理', roles: ['security'] },
        component: () =>
          addProgressbar(
            import('@/views/rights-management/rights-management.vue'),
          ),
      },
      {
        path: 'pw-management',
        name: 'pw-management',
        meta: { title: '密码管理', roles: ['security'] },
        component: () =>
          addProgressbar(import('@/views/pw-management/pw-management.vue')),
      },
      {
        path: 'catalog-management',
        name: 'catalog-management',
        meta: { title: '层级定义', roles: ['system'] }, // 系统管理员页面
        component: () =>
          addProgressbar(
            import('@/views/catalog-management/catalog-management.vue'),
          ),
      },
      {
        path: 'catalog-personal',
        name: 'catalog-personal',
        meta: {
          title: '层级定义',
          roles: ['normal'], // 用户界面
          breadcrumb: [
            { label: '设置' },
            {
              label: '当前页面',
              path: '/private/catalog-personal',
              breadcrumb: [{ label: '设置' }, { label: '层级定义' }],
            },
          ],
        },
        component: () =>
          addProgressbar(
            import('@/views/catalog-personal/catalog-personal.vue'),
          ),
      },
      {
        path: 'audit-management',
        name: 'audit-management',
        meta: {
          title: '审计',
          // roles: ['normal'],
          // roles: ['system'],
          roles: ['audit'],
          breadcrumb: [{ label: '审计', path: '/private/audit-management' }],
        }, // 系统管理员页面
        component: () =>
          addProgressbar(
            import('@/views/audit-management/audit-management.vue'),
          ),
      },
      {
        path: 'security-setting',
        name: 'security-setting',
        meta: {
          title: '安全设置',
          roles: ['normal'],
          breadcrumb: [{ label: '设置' }, { label: '安全设置' }],
        },
        component: () =>
          addProgressbar(
            import('@/views/security-setting/security-setting.vue'),
          ),
      },
      {
        path: 'favorites',
        name: 'favorites',
        meta: {
          title: '收藏夹',
          roles: ['normal'],
          breadcrumb: [{ label: '当前页面' }],
        },
        component: () =>
          addProgressbar(import('@/views/favorites/favorites.vue')),
      },
      {
        path: 'tag-management',
        name: 'tag-management',
        meta: {
          title: '标签管理',
          roles: ['system'],
          breadcrumb: [{ label: '平台管理' }, { label: '标签管理' }],
        },
        component: () =>
          addProgressbar(import('@/views/tag-management/tag-management.vue')),
      },
      {
        path: 'file-type-management',
        name: 'file-type-management',
        meta: {
          title: '文件格式管理',
          roles: ['system'],
          breadcrumb: [{ label: '当前页面' }],
        },
        component: () =>
          addProgressbar(
            import('@/views/file-type-management/file-type-management.vue'),
          ),
      },
      {
        path: 'backup-setting',
        name: 'backup-setting',
        meta: {
          title: '数据备份设置',
          roles: ['system'],
          breadcrumb: [{ label: '当前页面' }],
        },
        component: () =>
          addProgressbar(import('@/views/backup-setting/backup-setting.vue')),
      },
      {
        path: 'recycle-bin',
        name: 'recycle-bin',
        meta: {
          title: '回收站',
          roles: ['normal', 'system'],
          breadcrumb: [{ label: '当前页面' }],
        },
        component: () =>
          addProgressbar(import('@/views/recycle-bin/recycle-bin.vue')),
      },
      {
        path: 'operation-log/:id',
        name: 'operation-log',
        meta: {
          title: '查看操作记录',
          breadcrumb: [
            { label: '数据库管理' },
            { label: '项目数据', path: '/private/db-management/project' },
            { label: '当前页面' },
          ],
          roles: ['normal'],
          hasBack: true,
        },
        component: () =>
          addProgressbar(import('@/views/operation-log/operation-log.vue')),
      },
      {
        path: 'operation-log-personal/:id',
        name: 'operation-log-personal',
        meta: {
          title: '查看操作记录',
          breadcrumb: [
            { label: '数据库管理' },
            { label: '个人数据', path: '/private/db-management/personal' },
            { label: '当前页面' },
          ],
          roles: ['normal'],
          hasBack: true,
        },
        component: () =>
          addProgressbar(import('@/views/operation-log/operation-log.vue')),
      },
      {
        path: 'operation-log-library/:id',
        name: 'operation-log-library',
        meta: {
          title: '查看操作记录',
          breadcrumb: [
            { label: '数据库管理' },
            { label: '库数据', path: '/private/db-management/library' },
            { label: '当前页面' },
          ],
          roles: ['normal'],
          hasBack: true,
        },
        component: () =>
          addProgressbar(import('@/views/operation-log/operation-log.vue')),
      },
      {
        path: 'operation-log-file/:id',
        name: 'operation-log-file',
        meta: {
          title: '查看操作记录',
          breadcrumb: [{ label: '回收站' }, { label: '当前页面' }],
          roles: ['normal', 'system'],
          hasBack: true,
        },
        component: () =>
          addProgressbar(import('@/views/operation-log/operation-log.vue')),
      },
      {
        path: 'db-management/project/embed',
        name: 'db-management/project/embed',
        meta: {
          title: '项目数据',
          breadcrumb: [{ label: '数据库管理' }, { label: '当前页面' }],
          roles: ['normal'],
          type: 'project',
        },
        component: () =>
          addProgressbar(
            import('@/views/db-management/db-management-embed.vue'),
          ),
      },
      {
        path: 'db-management/library/embed',
        name: 'db-management/library/embed',
        meta: {
          title: '库数据',
          breadcrumb: [{ label: '数据库管理' }, { label: '当前页面' }],
          roles: ['normal'],
          type: 'library',
        },
        component: () =>
          addProgressbar(
            import(
              '@/views/db-management-library/db-management-library-embed.vue'
            ),
          ),
      },
      {
        path: 'db-management/library/embed-for-query-list-by-category-id',
        name: 'db-management/library/embed-for-query-list-by-category-id',
        meta: {
          title: '库数据',
          breadcrumb: [{ label: '数据库管理' }, { label: '当前页面' }],
          roles: ['normal'],
          type: 'library',
        },
        component: () =>
          addProgressbar(
            import(
              '@/views/db-management-library/db-management-library-embed-for-query-list-by-category-id.vue'
            ),
          ),
      },
      {
        path: 'db-management/engineering/embed',
        name: 'db-management/engineering/embed',
        meta: {
          title: '工程数据',
          breadcrumb: [{ label: '数据库管理' }, { label: '当前页面' }],
          roles: ['normal'],
          type: 'engineering',
        },
        component: () =>
          addProgressbar(
            import(
              '@/views/db-management-engineering/db-management-engineering-embed.vue'
            ),
          ),
      },
      {
        path: 'db-management/engineering/embed-for-query-list-by-category-id',
        name: 'db-management/engineering/embed-for-query-list-by-category-id',
        meta: {
          title: '工程数据',
          breadcrumb: [{ label: '数据库管理' }, { label: '当前页面' }],
          roles: ['normal'],
          type: 'engineering',
        },
        component: () =>
          addProgressbar(
            import(
              '@/views/db-management-engineering/db-management-engineering-embed-for-query-list-by-category-id.vue'
            ),
          ),
      },
    ],
  },
  {
    path: '/sign',
    name: 'sign',
    component: () => import('@/layout/sign-layout/sign-layout.vue'),
    children: [
      {
        path: 'db-management-embed-auto-login',
        name: 'db-management-embed-auto-login',
        component: () =>
          import('@/views/db-management/db-management-embed-auto-login.vue'),
      },
      {
        path: 'db-management-library-embed-auto-login',
        name: 'db-management-library-embed-auto-login',
        component: () =>
          import(
            '@/views/db-management-library/db-management-library-embed-auto-login.vue'
          ),
      },
      {
        path: 'db-management-library-embed-auto-login-for-query-list-by-category-id',
        name: 'db-management-library-embed-auto-login-for-query-list-by-category-id',
        component: () =>
          import(
            '@/views/db-management-library/db-management-library-embed-auto-login-for-query-list-by-category-id.vue'
          ),
      },
      {
        path: 'db-management-engineering-embed-auto-login',
        name: 'db-management-engineering-embed-auto-login',
        component: () =>
          import(
            '@/views/db-management-engineering/db-management-engineering-embed-auto-login.vue'
          ),
      },
      {
        path: 'db-management-engineering-embed-auto-login-for-query-list-by-category-id',
        name: 'db-management-engineering-embed-auto-login-for-query-list-by-category-id',
        component: () =>
          import(
            '@/views/db-management-engineering/db-management-engineering-embed-auto-login-for-query-list-by-category-id.vue'
          ),
      },
      {
        path: 'db-management-engineering-embed-auto-login-page',
        name: 'db-management-engineering-embed-auto-login-page',
        component: () =>
          import(
            '@/views/db-management-engineering/db-management-engineering-embed-auto-login-page.vue'
          ),
      },
      {
        path: 'login',
        name: 'login',
        component: () => import('@/views/login/login.vue'),
        beforeEnter(to, from) {
          let accountStore = useAccountStore()
          let account = storeToRefs(accountStore)
          /**
           * 登录状态禁止到登录页
           */
          if (account.token.value) {
            return '/'
          }
        },
      },
    ],
  },
  {
    path: '/:catchAll(.*)',
    component: () => import('@/views/error-page/error-page.vue'),
  },
]

if (import.meta.env.DEV) {
  routes.unshift({
    path: '/example-components',
    name: 'example-components',
    component: () =>
      import('@/views/example/example-components/example-components.vue'),
  })
  routes.unshift({
    path: '/example-api',
    name: 'example-api',
    component: () => import('@/views/example/example-api.vue'),
  })
  routes.unshift({
    path: '/example-excel',
    name: 'example-excel',
    component: () => import('@/views/example/example-excel.vue'),
  })
  routes.unshift({
    path: '/example-docx',
    name: 'example-docx',
    component: () => import('@/views/example/example-docx.vue'),
  })
  routes.unshift({
    path: '/example-csv',
    name: 'example-csv',
    component: () => import('@/views/example/example-csv.vue'),
  })
  routes.unshift({
    path: '/example-json',
    name: 'example-json',
    component: () => import('@/views/example/example-json.vue'),
  })
  routes.unshift({
    path: '/example-code',
    name: 'example-code',
    component: () => import('@/views/example/example-code.vue'),
  })
  routes.unshift({
    path: '/example-vtk',
    name: 'example-vtk',
    component: () => import('@/views/example/example-vtk.vue'),
  })
  routes.unshift({
    path: '/example-model',
    name: 'example-model',
    component: () => import('@/views/example/example-model.vue'),
  })
  // routes.unshift({
  //   path: '/example-agent',
  //   name: 'example-agent',
  //   component: () => import('@/views/example/example-agent/example-agent.vue'),
  // })
}

let privateRoute = routes.find(({ name }) => name === 'private')
privateRoute?.children?.forEach?.(route => {
  let component = route.component
  route.component = function (...arg) {
    let roleStore = useRoleStore()
    let { role } = storeToRefs(roleStore)
    //有角色权限就访问原本预定的页面
    if (
      role.value.some(
        r =>
          route?.meta?.roles instanceof Array && route?.meta?.roles.includes(r),
      )
    ) {
      return component(...arg)
    }
    return import('@/views/error-page/error-page.vue')
  }
  route.beforeEnter = async (to, from, next) => {
    //每次进来都是一个新的
    router.removeRoute(to.name)
    router.addRoute(
      'private',
      privateRoute?.children?.find(({ name }) => name === to.name),
    )
    try {
      let roleStore = useRoleStore()
      let { role } = storeToRefs(roleStore)
      if (role.value.length === 0) {
        await roleStore.update()
      }
      next()
    } catch (e) {
      Message.warn(e?.message || e)
      next('/sign/login')
    }
  }
})

routes.unshift({
  path: '/',
  beforeEnter: async (to, from, next) => {
    /**
     * 登录相关
     */
    let accountStore = useAccountStore()
    let account = storeToRefs(accountStore)
    if (!account.token.value) {
      next('/sign/login')
    }
    try {
      /**
       * 角色相关
       */
      let roleStore = useRoleStore()
      let { role } = storeToRefs(roleStore)
      //如果没有角色数据先刷新
      if (role.value.length === 0) {
        await roleStore.update()
      }
      let route = privateRoute?.children?.find(route => {
        return role.value.some(
          r =>
            route?.meta?.roles instanceof Array &&
            route?.meta?.roles.includes(r),
        )
      })
      if (route) {
        return next(path.join('/private', route.path))
      }
      Message.warn('你还没有访问权限的页面！')
      accountStore.logout()
      next('/sign/login')
    } catch (e) {
      Message.warn(e?.message || e)
      accountStore.logout()
      next('/sign/login')
    }
  },
  component: {
    render() {
      return h('div', 'loading')
    },
  },
})

let router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
})
router.onError(error => {
  //捕获切换页面，因为页面更新报错的情况
  Modal.confirm({
    title: import.meta.env.DEV ? '错误信息' : '系统信息',
    icon: createVNode(ExclamationCircleOutlined),
    content: import.meta.env.DEV ? error : '应用可能已更新,请刷新.',
    onOk() {
      window.location.reload(true)
    },
    onCancel() {},
  })
})

export default router
